/**
 * Licensed to the Apache Software Foundation (ASF) under one or more contributor license
 * agreements.  See the NOTICE file distributed with this work for additional information regarding
 * copyright ownership.  The ASF licenses this file to you under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with the License.  You may obtain
 * a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package org.apache.zookeeper.server;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;
import java.util.Collections;

import org.apache.jute.InputArchive;
import org.apache.jute.OutputArchive;
import org.apache.jute.Record;
import org.apache.zookeeper.data.Stat;
import org.apache.zookeeper.data.StatPersisted;

/**
 * This class contains the data for a node in the data tree.
 * <p>
 * A data node contains a reference to its parent, a byte array as its data, an
 * array of ACLs, a stat object, and a set of its children's paths.
 *
 */
public class DataNode implements Record {
    private static final Set<String> EMPTY_SET = Collections.emptySet();
    /**
     * 这个node的状态，将会被持久化到磁盘
     */
    public StatPersisted stat;
    /**
     * 当前节点的父节点
     */
    DataNode parent;
    /**
     * 当前节点的数据
     */
    byte data[];
    /**
     * 节点acl权限控制
     */
    Long acl;
    /**
     *
     * 当前节点的子节点path 。
     * 子节点path不包含父节点path部分，仅仅是最后一部分的path。
     * 在修改这个变量的时候，需要在synchronized中，除了反序列化操作（为了加速反序列化）。
     */
    private Set<String> children = null;

    DataNode() {
    }

    public DataNode(DataNode parent, byte data[], Long acl, StatPersisted stat) {
        this.parent = parent;
        this.data = data;
        this.acl = acl;
        this.stat = stat;
    }

    //    ================== 当前节点的子节点path ==================
    public synchronized boolean addChild(String child) {
        if (children == null) {
            children = new HashSet<String>(8);
        }
        return children.add(child);
    }
    public synchronized boolean removeChild(String child) {
        if (children == null) {
            return false;
        }
        return children.remove(child);
    }
    public synchronized Set<String> getChildren() {
        if (children == null) {
            return EMPTY_SET;
        }

        return Collections.unmodifiableSet(children);
    }
    public synchronized void setChildren(HashSet<String> children) {
        this.children = children;
    }
    //    ================== 当前节点的子节点path 结束==================


    synchronized public void copyStat(Stat to) {
        to.setAversion(stat.getAversion());
        to.setCtime(stat.getCtime());
        to.setCzxid(stat.getCzxid());
        to.setMtime(stat.getMtime());
        to.setMzxid(stat.getMzxid());
        to.setPzxid(stat.getPzxid());
        to.setVersion(stat.getVersion());
        to.setEphemeralOwner(stat.getEphemeralOwner());
        to.setDataLength(data == null ? 0 : data.length);
        int numChildren = 0;
        if (this.children != null) {
            numChildren = children.size();
        }
        // 为何复制Cversion状态的时候，要使用这种计算方法？
        // 解：首先我们要明白cversion表示："节点的子节点列表变化版本号"：详情见：Stat#cversion
        //     由于zk只在创建节点的时候对其父节点的cversion++，在删除该节点的时候，并没有对其父节点的cversion--;也就是zk database中真实存储的cversion的值表示父节点下创建过多少子节点。
        //     理论上来说：对于父节点下子节点的‘创建和删除’操作，都应该对cversion++，而当前父节点存在多少个子节点numChildren，就说明还有多少个子节点未删除。那么未删除的子节点，cversion版本号是不会增加的，
        //     所以    创建子节点数 * 2 表示子节点创建和删除操作对应的版本号，所以   cversion = cversion*2- 未删除子节点个数 = cversion*2- 现存子节点个数 =  cversion*2- numChildren
        to.setCversion(stat.getCversion() * 2 - numChildren);
        to.setNumChildren(numChildren);
    }

    @Override
    synchronized public void deserialize(InputArchive archive, String tag) throws IOException {
        archive.startRecord("node");
        data = archive.readBuffer("data");
        acl = archive.readLong("acl");
        stat = new StatPersisted();
        stat.deserialize(archive, "statpersisted");
        archive.endRecord("node");
    }

    @Override
    synchronized public void serialize(OutputArchive archive, String tag) throws IOException {
        archive.startRecord(this, "node");
        archive.writeBuffer(data, "data");
        archive.writeLong(acl, "acl");
        stat.serialize(archive, "statpersisted");
        archive.endRecord(this, "node");
    }
}
